/**
 * Created by PR on 2016/1/28.
 */
/* 手机验证 */
var mobile = null;
var vcode_type = null;
var vcode =  null;
/* 注册密码昵称 */
var newPsd = null; //是否为密码找回
var phoneNum = null;
/* 注册完善信息 */
var areaSave = null;
var tasteSave = null;
var localCity = false;
var userDistrict = null;
var userCategory = null;
var favoriteBusiness = null;
var page = null;
var time = null;
var control = null;
var isSend = false;

                                                                    /* 注册partOne --start */
/* code timeCount */
function timeCount() {
    --time;
    if(time <= 0) {
        $('.btn-sendCode').text('发送验证码');
         $(".btn-sendCode").removeAttr("disabled");
        $('.btn-sendCode').removeClass('sent');
        isSend = false;
        clearInterval(control);
    } else if(time < 59){
        $('.btn-sendCode').text('剩余' + time + '秒');
        $(".btn-sendCode").attr({"disabled":"disabled"});
    }
}
function bindSendCode() {
    $('.btn-sendCode').click(function () {
        event.stopPropagation();
        $(this).addClass('sent');
        time = 60;
        $(this).text('剩余59秒');
        control =  setInterval(timeCount,1000);
    });
}
function startTime(target) {
    $(target).addClass('sent');
    time = 60;
    $(target).text('剩余59秒');
    control =  setInterval(timeCount,1000);
}
/* 手机验证码 */
function sendCode(target) {
    mobile = $("#phoneNumber").val();
    if(newPsd) {
        vcode_type = 2;
    } else {
        vcode_type = 1;
    }
    var url = "/Account/sendVcode/";
    var arg = {};
    arg.mobile = mobile;
    arg.vcode_type = vcode_type;
    ajaxJsonp(url,arg,sendSuc,"get",regFail);
    /* identify code for phone */
    function sendSuc(res) {
        var msg = res.status.msg;
        showModal(msg);
        if(!isSend) {
            if(checkMobile()){
                startTime(target);
            }
        }
        isSend = true;
    }
}

/*注册不成功的返回消息*/
function regFail(res){
    var msg = res.status.msg;
    showModal(msg);
}
function confirmPhoneNumber() {
    mobile = $("#phoneNumber").val();
    vcode = $('#idfCode').val();
    if(newPsd) {
        var url = "/Account/findPassword";
        var arg = {};
        arg.mobile = mobile;
        arg.vcode = vcode;
        arg.password = $("#psd").val();
        ajaxJsonp(url,arg,registerSuc);
    } else {
        var url = "/Account/verifyVcode/";
        var arg = {};
        arg.mobile = mobile;
        arg.vcode = vcode;
        arg.vcode_type = 1;
        ajaxJsonp(url,arg,registerSuc);
    }
}
/* 验证成功 */
function registerSuc(res) {
    var msg = res.status.msg;
    showModal(msg);
    if(newPsd) {
        var url = "../login/login.html";
        doJump(url);
    } else {
        var url = "registerPsd.html?phoneNumber=" + $('#phoneNumber').val();
        doJump(url);
    }
}
                                                                    /* 注册partOne --end */
                                                                    /* 注册partTwo --star */
function register() {
    var password = idfPsd();
    if(password) {
        var arg = {};
        var url = "/Account/register";
        arg.mobile = phoneNum;
        arg.url = url;
        arg.password = password;
        arg.nickname = $("#nick-name").val();
        ajaxJsonp(url, arg, registerPsdSuc);
    }
}
function idfPsd() {
    if(!$('#phoneNumber').val()) {
        $('.modal-body').text("请输入账号");
        $('#myModal').modal();
        return false;
    }
    if(!$('#psd').val() || !$('#idfPsd').val()) {
        $('.modal-body').text("请输入密码");
        $('#myModal').modal();
        return false;
    }
    if($('#psd').val() === $('#idfPsd').val()) {
        return $('#psd').val();
    } else {
        $('.modal-body').text("两次输入的密码不一致");
        $('#myModal').modal();
        return false;
    }
}
/* 注册成功  */
function registerPsdSuc(res) {
    var msg = res.status.msg;
    showModal(msg);
    saveCookie("token", res.data.token, 20, "path=/");
    var url = "registerImage.html";
    doJump(url);
}
                                                                         /* 注册partTwo --end */
                                                                         /* 注册partThree --start */
/* 获取头像 */
function getUserDetail() {
    var url = "/UserCenter/getUserDetail";
    var arg = {};
    ajaxJsonp(url, arg, renderUserDetail);
}
function renderUserDetail(res) {
    var user = res.data.user_info;
    var html = '';
    if(user.avatar) {
        html += '<img src="'+ user.avatar +'" id="user-headImage" class="user-headImage-set"/>';
    } else {
        html += '<img src="../../resource/images/head-image.jpg" id="user-headImage" class="user-headImage-set"/>'
    }
    $(".target-word").before(html);
    getDefaultAvatar();
    resizeableImage($('.resize-image'));
}
/* 获取默认头像 */
function getDefaultAvatar() {
    var url = "/UserCenter/getDefaultAvatar";
    var arg = {};
    ajaxJsonp(url, arg, renderDefaultAvatar);
}
/* 渲染头像列表 */
function renderDefaultAvatar(res) {
    var datas = res.data;
    console.log(res);
    var html = '<ul>';
    for(var i = 0; i<datas.length; i++) {
        html += '<li><img data-id="'+ datas[i].id +'" src="'+ datas[i].url +'" onclick="choseImage(this)"/></li>';
    }
    html += '</ul>';
    $(".user-default").append(html);
}
/* choseImage */
function choseImage(target) {
    var src = $(target).attr("src");
    var id = $(target).attr("data-id");
    $("#user-headImage").attr("src", src);
    saveDefaultAvatar(id);
}
function saveDefaultAvatar(id) {
    var url = "/UserCenter/saveDefaultAvatar";
    var arg = {};
    arg.id = id;
    ajaxJsonp(url, arg);
}
/* imgPage-定义页面跳转 */
function perfectInfo() {
    if(1 != 1) {
    } else {
        var url = "registerPerfectInfo.html";
        location.href = url;
    }
}
                                                                    /* 注册partThree --end */
                                                                    /* 注册partFour --start */
/* registerPerfectInfo-注册页面初始化与事件控制 */
function setPage() {
    var $pages = $('.content');
    var pageNum = $pages.length;
    var pageWidth = $('.content:eq(0)').width();
    var width = pageWidth;
    if(!page) {
        $('.content').each(function () {
            pageWidth -= width;
            $(this).css('right', pageWidth + 'px');
        });
    }
    /* 保存商区 */
    $('.btn-info-next').click(function () {
        console.log(1);
        saveBusinessDistrict();
    });
    /* 保存商区 */
    function saveBusinessDistrict() {
        var url = "/Account/saveBusinessDistrict";
        var arg = {};
        var name = [];
        var noChoose = false;
        var token = getArg("token");
        /* 判断是否选择商区 -- start */
        $(".area-name").each(function() {
            if($(this).hasClass("choose")) {
                name.push( $(this).attr("id"));
                noChoose = true;
            }
        });
        if(!noChoose) {
            msg = "请选择商区";
            showModal(msg);
            return
        }
        /* 判断是否选择商区 -- end */
        name = name.join("-");
        arg.business_district_ids = name;
        arg.token = token;
        ajaxJsonp(url, arg, saveAreaSuc);
    }
    /* 选择商区保存成功后，滑动页面 */
    function saveAreaSuc(res) {
        if(page) {
            var msg = "保存成功"
            showModal(msg);
            var url = "../userInfo/userInfoSetting.html";
            doJump(url);
        } else {
            var $this = $(".first").next();
            $this.show().siblings().hide();
            for (var i = 0; i < pageNum; i++) {
                var right = $($pages[i]).css('right');
                right = parseInt(right);
                right += width;
                $($pages[i]).animate({right: + right + 'px'},200);
            }
        }

    }
    /* 保存所选标签 */
    $(".btn-save-taste").click(function() {
        /* 判断是否已经储存过一次 */
        /* 判断是否选择标签 */
        var isChoose = false;
        var ids = [];
        $(this).parent()
            .find("li").each(function() {
                if($(this).hasClass("active")) {
                    ids.push($(this).attr("data-id"));
                    isChoose = true;
                }
            });
        if(!isChoose) {
            showModal("请选择你喜欢的标签");
            setTimeout(function(){
                $("#myModal").modal("hide");
            },1000);
        }
        /* 进行保存请求 */
        ids = ids.join("-");
        saveCategory(ids);
    });
    /* 保存标签 */
    function saveCategory(ids) {
        var url = "/Account/saveCategory";
        var arg = {};
        arg.category_ids = ids;
        ajaxJsonp(url, arg, saveTasteSuc);
    }
    /* 喜欢标签保存成功 */
    function saveTasteSuc(res) {
        if(page) {
            var msg = "保存成功"
            showModal(msg);
            var url = "../userInfo/userInfoSetting.html";
            doJump(url);
        } else {
            var $this = $(".second").next();
            $this.show().siblings().hide();
            for (var i = 0; i < pageNum; i++) {
                var right = $($pages[i]).css('right');
                right = parseInt(right);
                right += width;
                $($pages[i]).animate({right: + right + 'px'}, 200);
            }
        }
    }
    /* 去到上一个part */
    $('.info-prev').click(function() {
        if(page) {
            if($(".local-pos").hasClass("classAdd")) {
                $(".local-pos").removeClass("classAdd");
                location.href = "registerPerfectInfo.html?page=0";
                return
            } else {
                location.href = "../userInfo/userInfoSetting.html?url=1";
                return
            }
        } else {
            var $this = $(this).parent().parent();
            var $index = $pages.index(($(this).parent().parent()));
            if($index == 0) {
                if($(".local-pos").hasClass("classAdd")){
                    $(".local-pos").removeClass("classAdd");
                    location.href="registerPerfectInfo.html?url=1";
                    return
                }else{
                    location.href="registerImage.html?url=1";
                }
            } else {
                var $target = $this.prev();
                $target.show().siblings().hide();
                for (var i = 0; i < pageNum; i++) {
                    var right = $($pages[i]).css('right');
                    right = parseInt(right);
                    right -= width;
                    $($pages[i]).animate({right: + right + 'px'}, 200);
                }
            }
        }
    });
    /* 跳过这一part */
    $(".info-next").click(function() {
        var $this = $(this).parent().parent();
        var $index = $pages.index(($(this).parent().parent()));
        if($index == 2) {
            var url = "../../index.html?";
            doJump(url);
            return
        } else {
            var $target = $this.next();
            $target.show().siblings().hide();
            for (var i = 0; i < pageNum; i++) {
                var right = $($pages[i]).css('right');
                right = parseInt(right);
                right += width;
                $($pages[i]).animate({right: + right + 'px'}, 200);
            }
        }
    })
}
/* 获取用户喜欢的类型 */
function getFavoriteOptions() {
    var url = "/Account/getFavoriteOptions";
    var arg = {};
    ajaxJsonp(url, arg, renderFavoriteOptions);
}
/* 渲染用户喜欢类型 */
function renderFavoriteOptions(res) {
    var data = res.data;
    for(var i = 0; i < data.length; i++) {
        var items = data[i].items
        var length = items.length;
        var html =  '';
        html += '<h3 class="cook-type">' + data[i].name + '</h3>';
        html += '<div class="type-list"><ul>';
        for(var j = 0; j < length; j++) {
            if((j == 3 || j == 7 || j == 11)&& j != length) {
                html += '<li data-id="'+ items[j].id + '">'+ items[j].name + '</li></ul><ul>';
            }
            if(j == length) {
                html += '<li data-id="'+ items[j].id + '">'+ items[j].name + '</li></ul></div>';
            }
            html += '<li data-id="'+ items[j].id + '">'+ items[j].name + '</li>';
        }
        $(".prefer-box").append(html);
    }
    if(userCategory) {
        $(".prefer-box li").each(function(){
            for(var i = 0; i<userCategory.length; i++) {
                if($(this).attr('data-id') == userCategory[i]) {
                    $(this).addClass("active");
                }
            }
        });
        $(".btn-save-taste").text("完成");
    }
    targetBind();
}
/* 获取商家 */
function getFavoriteBusinessOptions() {
    var url = "/Account/getFavoriteBusinessOptions";
    var arg = {};
    ajaxJsonp(url, arg, renderFavoriteBusinessOptions);
}
/* 渲染商家 */
function renderFavoriteBusinessOptions(res) {
    var datas = res.data;
    var length = datas.length;
    var html = "";
    for(var i = 0; i < length; i++) {
        html += '<li data-id="' + datas[i].id + '">' +  datas[i].name + '</li>';
    }
    $(".seller-list ul").append(html);
    sellerChooseBind();
    if(favoriteBusiness) {
        $(".seller-list li").each(function(){
            for(var i = 0; i<favoriteBusiness.length; i++) {
                if($(this).attr("data-id") == favoriteBusiness[i].id) {
                    $(this).addClass("choose");
                }
            }
        });
    }
}
/*perfect information */
/* 标签点击事件绑定 */
function targetBind() {
    $('.type-list ul li').click(function() {
        $(this).toggleClass("active");
    });
}
/* 给商家绑定事件 */
function sellerChooseBind() {
    $('.seller-list li').click(function() {
        $(this).toggleClass('choose');
    });
}
/* 手机验证 */
function checkMobile() {
    var isMobile=/^(?:13\d|15\d|18\d)\d{5}(\d{3}|\*{3})$/;
    var phNum = $("#phoneNumber").val();
    var mob=$.trim($("#phoneNumber").val());
    if($.trim($("#phoneNumber").val())=="") {
        return false;
    }
    if(!isMobile.test(phNum)) {
        return false;
    }
    return true
}

/* 初始化页面 */
function innit() {
    if(!page) {
        var myCity = new BMap.LocalCity();
        myCity.get(getPosition);
    } else {
        if(page == 0) {
            var myCity = new BMap.LocalCity();
            myCity.get(getPosition);
        } else if(page == 1) {
            getUserCategory();
        } else if(page == 2) {
            getFavoriteBusiness();
        }
    }
}
/* 获取用户选择商区 */
function getUserBusinessDistrict() {
    var url = "/UserCenter/getUserBusinessDistrict";
    var arg = {};
    ajaxJsonp(url, arg, setUserBusinessDistrict);
}
/* 设置商区 */
function setUserBusinessDistrict(res) {
    console.log(res);
    var data = res.data;
    var city = data.city_name;
    var id = data.city_id;
    var chooseCity = getCookie("city");
    if(city&&city!=chooseCity) {
        $(".local-pos").text(chooseCity);
        getBusinessDistrict();
    } else if(city == chooseCity){
        $(".local-pos").text(chooseCity);
        getBusinessDistrict();
    }
    else {
        getCity();
    }
    if(data.business_district_id.length > 0) {
        userDistrict = data.business_district_id;
    }
}
/* 获取用户喜好 */
function getUserCategory() {
    var url = "/UserCenter/getUserCategory";
    var arg = {};
    ajaxJsonp(url, arg, setUserCategory);
}
/* 设置喜好 */
function setUserCategory(res) {
    var data = res.data;
    if(data.user_category) {
        userCategory = data.user_category;
    }
    getFavoriteOptions();
}
/* 获取用户喜欢商家 */
function getFavoriteBusiness() {
    var url = "/UserCenter/getFavoriteBusiness";
    var arg = {};
    ajaxJsonp(url, arg, setFavoriteBusiness);
}
/* 设置喜欢商家 */
function setFavoriteBusiness(res) {
    var data = res.data;
    if(data.length > 0) {
        favoriteBusiness = data;
    }
    getFavoriteBusinessOptions();
}
/* 初始化其余部分页面 */
function initPage() {
    getFavoriteBusinessOptions();
    getFavoriteOptions();
}
/* 获取本地位置 */
function getPosition(result){
    var cityName = result.name;
    $(".local-pos").text(cityName);
    if(cityName) {
        saveCookie("city", cityName, 20, "path=/");
        console.log(document.cookie);
        getBusinessDistrict();
    } else {
        getCity();
    }
    initPage();
}
/* 请求城市 */
function getCity() {
    $(".local-pos").addClass("classAdd");
    var url = "/Account/getCity";
    var arg = {};
    ajaxJsonp(url, arg, loadCitySuc);
}
/* 渲染城市 */
function loadCitySuc(res) {
    showModal("请选择城市");
    $(".city-box").show();
    $(".area-detail").text("");
    $(".words_list").fadeIn();
    $(".main-content").fadeOut();
    var citySrcList=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
    for(var i = 0; i < citySrcList.length; i++) {
        var add_letter='<li id=' + citySrcList[i] + '><a class="title">' + citySrcList[i] + '</a><ul class="a_detail"></ul></li>';
        $("ul.city-box").append(add_letter);
    }
    for(var i = 0; i < res.data.length; i++) {
        for(var i = 0; i < res.data.length; i++){
            var areaName = res.data[i].areaname;  //城市的名字
            var pinyin = res.data[i].pinyin;     //城市的拼音
            var id = res.data[i].position.split(" ")[1];
            var first_letter = pinyin.charAt(0);
            var add_city = '<li><a data-id=' + id + ' href="javascript:void(0)" onclick="choose(this)">' + areaName + '</a></li>';
            $("#" + first_letter + " .a_detail").append(add_city);
        }
    }
}
/* 选择城市 */
function choose(target) {
    var city_name = $(target).text();
    var id = $(target).attr("data-id");
    $(".local-pos").removeClass("classAdd");
    $(".city-box").hide();
    $(".main-content").fadeToggle();
    $(".local-pos").attr("data-id", id);
    $(".local-pos").text(city_name);
    saveCookie("city", city_name, 20, "path=/");
    getBusinessDistrict();
}
/* 获取商区 */
function getBusinessDistrict() {
    var url = "/Account/getBusinessDistrict";
    var arg = {};
    $(".area-list").hide();
    ajaxJsonp(url, arg, renderBusinessDistrict);
}
/* 渲染城市下商区 */
function renderBusinessDistrict(res) {
    var area = res.data;
    var html = "";
    for(i in area) {
        html += '<a href="javascript:void(0)" class="area-name needsclick" id=' + area[i].id + '>' + area[i].areaname + '</a>';
    }
    $(".area-detail").append(html);
    if(userDistrict) {
        $(".area-list a").each(function () {
            for(var i = 0; i < userDistrict.length; i++) {
                if($(this).attr("id") == userDistrict[i]) {
                    $(this).addClass("choose");
                }
            }
        })
    }
    $(".area-list").show();
    $(".local-pos").show();
    $(".usualArea").show();
    choseEvenBind();
}
/* 选择商区时标记切换 */
function choseEvenBind() {
    $(".area-name").click(function() {
        $(this).toggleClass("choose");
    });
}
/* 保存喜欢的商家 */
$(".btn-info-completed").click(function() {
    var $list = $(".seller-list ul li");
    var save = false;
    var ids = [];
    $list.each(function () {
        if($(this).hasClass("choose")) {
            ids.push($(this).attr("data-id"));
            save = true;
        }
    });
    if(save) {
        ids = ids.join("-");
        doGiving(ids);
        saveFavoriteBusiness(ids);
    } else {
        var msg = "请选择你喜欢的商家";
        showModal(msg);
    }
});
/* 给赞 */
function doGiving(ids) {
    var ids = ids.split("-");
    if(ids.length > 0) {
        for(var i = 0; i<ids.length; i++) {
            addShopUserGiving(ids[i]);
        }
    }
}
function addShopUserGiving(id) {
    var url = "/Shops/addShopUserGiving";
    var arg = {};
    arg.shop_id = id;
    ajaxJsonp(url, arg);
}
/* 保存选择商家 */
function saveFavoriteBusiness(ids) {
    var url = "/Account/saveFavoriteBusiness";
    var arg = {};
    arg.shop_ids = ids;
    ajaxJsonp(url, arg, saveFavoriteBusinessSuc);
}
/* 保存成功 */
function saveFavoriteBusinessSuc(res) {
    if(page) {
        var msg = "保存成功"
        showModal(msg);
        var url = "../userInfo/userInfoSetting.html";
        doJump(url);
    } else {
        var url = "../../index.html?";
        var msg = "保存成功";
        showModal(msg);
        doJump(url);
    }
}
                                                                /* 注册partFour --end */